<style>
.el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label {
  line-height: 31px;
}
</style>
<template>
  <div>
    <query-table  ref="project_query_table" :page-size="20"
                  :table-max-height="tableMaxHeight"
                  :columns="columns"
                 :append-buttons="appendQueryButtons" :query-fields="queryFields"
                 :detail-fields="infoFields" base-url="/project_info" v-loading="isLoading"  dataRequestMethod="post"
                 :after-load-detail="(data)=>{this.projectInfoList.push(data);}" selectable show-index />


    <el-dialog
        width="80%"
        title="导入数据"
        :visible="showFeaImport"
        :close-on-click-modal="false"
        @close="showFeaImport=false"
    >
      <el-main>
        <upload-excel v-if="!preEvaluationExcelData" :on-success="handleFileParseSuccess" :before-upload="beforeUpload"/>
        <excel-view v-if="preEvaluationExcelData" :data="preEvaluationExcelData"  max-height="500"></excel-view>
        <el-divider/>
        <el-button style="float: right" type="primary" :loading="isLoading" @click="importExcel">确认并导入</el-button>
        <el-button v-if="preEvaluationExcelData" style="float: right;margin-right:10px;" :loading="isLoading" @click="preEvaluationExcelData=null;">重新选择</el-button>
      </el-main>
    </el-dialog>
      <el-dialog :visible="showAdjustRate" :close-on-click-modal="false" @close="showAdjustRate=false">
        <div style="font-size:20px;text-align: center;padding-bottom: 10px;width:90%;margin: 0 auto;padding-top:30px">
          <span style="float:right;padding-right: 20px;margin-top: -20px;padding-bottom:5px;">
            <font style="font-size: 16px;color: black;font-weight: bold;padding-right: 335px">系数调整</font>
          </span>
          <record-table :columns="adjustRateColumns" :data="this.adjustRateData"></record-table>
          <el-button  type="primary" :loading="isLoading" @click="this.saveAdjustData">保存</el-button>
          <el-button @click="() =>{this.showTaskParam = false}">关闭</el-button>
        </div>
      </el-dialog>
    </div>
</template>
<script>
  import excel from "../../util/excel";
  export default {
    name: "ProjectList",
    props:{
      //页面最大高度
      pageHeight:{
        type:Number,
        default:500
      }
    },
    data() {
      return {
        isLoading:false,
        // multipleSelection: [],
        oilGasPoolMap:{},
        detailDlgVisible: false,
        loadingInfoDetail: false,
        //时间戳，用于组件key生成，防止复用或者重复渲染
        timestamp:new Date().getTime(),
        copyInfoDetail:{},
        taskDataList:[],
        taskInfo:{},
        showFeaImport: false,
        preEvaluationExcelData:null,
        projectInfoList:[],
        adjustRateData:[],
        showAdjustRate: false,
        //展示列信息
        columns: [
          {id: 'year',        name: '项目年度', width: 80,type:'user'},
          {id: 'name',        name: '项目名称',    align:'left'},
          {id: 'batchName',   name: '名称', align:'left'},
          // {id: 'versionName', name: '版本',    align:'left'},
          {id: 'buildOffice', name: '建设单位', width:120,type:'office',showOverflowTooltip:true},
          {id: 'totalInvest', name: '建设投资（万元）',  width:120,type:'office',showOverflowTooltip:true},
          {id: 'irrAfterTax', name: '税后内部收益率（%）',width:120, showOverflowTooltip:true},
          {id: 'pbpAfterTax', name: '税后投资回报期（年）', width:120,showOverflowTooltip:true},
          {id: 'npvAfterTax', name: '税后财务净现值（万元）', width:120, showOverflowTooltip:true},
          // {id: 'balancePrice', name: '基准平衡油价', width:120, showOverflowTooltip:true},
          {id: 'operation', name: '操作', type: 'button', width:200, children: [
              {text: '详情', type:'primary', click:(row)=>{ this.openPage('/evaluation/compute-version-list',row.id)}},
            {text: '删除', type:'danger', operation: 'delete',isHide:()=>{ return !this.checkPermission('project:delete')}},
              /*{text:'生成报告',type:'success',click:(row)=> this.createProjectReport(row.id)},*/
            ]
          },
        ],
        //查询条件字段
        queryFields: [
          {id: 'name', name: '项目名称', colSpan: 5},
          {id: 'year', name: '项目年度', component:'year-picker', colSpan: 4},
          {id: 'quality', name: '任务性质',colSpan:4,defaultValue:'out_put',component: {id: 'meta-select', type: 'batch-quality',load:this.loadBatchQuality,clearable:false,change:this.handleChangeQuality,}},
          {id: 'batchId', name: '名称', component:{id:'data-select',dataUrl: '/batch_info/nameList'}, colSpan: 5,isHide:(data)=>{return data.quality === "plan"}},
          {id: 'batchId', name: '名称', component:{id:'data-select',dataUrl: '/plan_info/nameList'}, colSpan: 5,isHide:(data)=>{return data.quality === "out_put"}},
          {id: 'buildOffice', name: '建设单位', component:{id:'company-select',hideRoot:true}, colSpan: 5},

          {id: 'batchName', name: '是否返回任务名称', defaultValue:true,isHide:()=>{return true}, colSpan: 8},

        ],
        appendQueryButtons:[
          // {text:'新增',type:'success',operation:'create'},
          // {text:'对比分析',type:'warning'},
          // {text:'生成报告',type:'warning'},
          // {text:'导出',click:this.downloadProjectData},
        ],
        infoFields: [{
          id: 'name',
          name: '名称',
          rules:[{ required: true, message: "请输入名称", trigger: "blur" }],
          colSpan:24,
        }, {
          id: 'year',
          name: '项目年度',
          component: 'year-picker',
          defaultValue:new Date().getFullYear(),
          rules:[{ required: true, message: "请输入项目年度", trigger: "blur" }],
        },
        // {
        //   id: 'taskName',
        //   name: '评价任务',
        //   disabled: true,
        //   defaultValue: this.taskInfo.name,
        // },
        //   {
        //   id: 'type',
        //   name: '项目类型',
        //   isDisabled:(item)=>{
        //     return this.detailDlgVisible;},
        //   component: {
        //     id:'meta-select',
        //     type:'project-type',
        //     change:this.handleChangeProjectType,
        //     rules:[{ required: true, message: "请输入项目年度", trigger: "blur" }],
        //   }
        // }, {
        //   id: 'grade',
        //   name: '项目级别',
        //   component: {
        //     id:'meta-select',
        //     type:'project-grade',
        //   }
        // },
          {
          id: 'buildOffice',
          name: '建设单位',
          defaultValue: this.$store.state.user.companyId,
          component: {id:'company-select',hideRoot:true},
        },
        //   {
        //   id: 'productType',
        //   name: '产品类型',
        //   component: {
        //     id:'meta-select',
        //     type:'product-type'
        //   }
        // }, {
        //   id: 'oilProperty',
        //   name: '油品性质',
        //   component: {
        //     id:'meta-select',
        //     type:'oil-property'
        //   }
        // }, {
        //   id: 'poolType',
        //   name: '油藏类型',
        //   component: {
        //     id:'meta-select',
        //     type:'oil-pool-type'
        //   },
        //   isHide:(row)=>{
        //     return row.productType ==='gas'
        //   }
        // }
        // ,{
        //   id: 'poolType',
        //   name: '气藏类型',
        //   component: {
        //     id:'meta-select',
        //     type:'gas-pool-type'
        //   },
        //   isHide:(row)=>{
        //     return !(row.productType ==='gas')
        //   }
        // }, {
        //   id: 'locationType',
        //   name: '地域',
        //   init: (data) => this.handleChangeBuildOffice(data.buildOffice,data),
        //   component: {
        //     id:'meta-select',
        //     type:'location-type'
        //   }
        // }, {
        //   id: 'extraEvaluateMethod',
        //   name: '评价方法',
        //   defaultValue: '',
        //   isDisabled:(item)=>{
        //     return item.id || this.detailDlgVisible;},
        //   component: {
        //     id:'radio',
        //     optionList:[{id:'',name:'现金流法'},{id:'subtract',name:'有无对比'}],
        //
        //   }
        // },
        ],
        adjustRateColumns:[

        ],
      }
    },
    computed:{
      //表格最大高度，自适应
      tableMaxHeight(){
        return this.pageHeight - 150;
      }
    },
    created() {
     // this.loadTask();
      // this.loadMetaMap('oil-pool-type',(dataMap)=>{
      //   for(let key in dataMap) {
      //     this.oilGasPoolMap[key] = dataMap[key];
      //   }
      // });
      // this.loadMetaMap('gas-pool-type',(dataMap)=>{
      //   for(let key in dataMap) {
      //     this.oilGasPoolMap[key] = dataMap[key];
      //   }
      // });

    },
    watch: {},
    methods: {

      // //处理多选
      // handleSelectionChange(val) {
      //   this.multipleSelection = val;
      // },
      // loadTask() {
      //   let taskId = this.$route.params.id;
      //   if (taskId) {
      //     this.$get("/project/task_info/info/" + taskId, {}, (response) => {
      //       if (response.data) {
      //         this.taskInfo = response.data;
      //       } else {
      //         this.$message.warning("评价任务不存在")
      //       }
      //     })
      //   } else {
      //
      //   }
      //
      // },
      loadBatchQuality(list) {
        let result = []
        for (let item of list) {
          if (item.id != 'reserves') {
            result.push(item)
          }
        }
        return result
      },
      handleChangeQuality(val,data) {
          data.batchId = '';
      },
      downloadProjectData() {
        this.$message.success("模拟导出");
      // window.open( this.$ctx+"/project/xx")
      },
      downloadMergeProjectData() {
        this.$message.success("模拟导出");
      },
      // 初始化调整系数
      initAdjustRate() {
        for (let i = 0; i < this.projectInfoList; i++) {
          let project = this.projectInfoList[i];
          let data = {
            index: i + 1,
            id: project.id,
            name: project.name,
          }
          this.adjustRateData.push(data)

        }
      },
      //删除选中项目
      deleteSelected() {
        if (!this.multipleSelection || this.multipleSelection.length <= 0) {
          this.$message.warning('未选中任何行');
          return;
        }

        this.$confirm('确定删除选中的'+this.multipleSelection.length+'条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var idList = [];
          for(var item of this.multipleSelection) {
            idList.push(item.id);
          }
            this.isLoading = true;
            this.$post("/project_info/delete_by_ids", {filterIdSet:idList}, (data) => {
              this.$message.success('删除成功！');
              this.$refs['project_query_table'].reload();
            }, (response) => {
              this.isLoading = false;
            });



        }).catch(() => {});
      },
      handleChangeBuildOffice(type,project) {
        if (type ===null || type =='' || type =='0') {
          project.locationType = '';
          return ;
        }
        // 新春 '4f4e0a8b3aa14ef686c5db21f10dd419'
        // 海洋 'c32df338e2ae4f74a728c4649bfc4588'
        /**
         * 新春--西部、海洋--海上、其他都是东部
         新建项目的时候加上级联，按照建设单位自动选择地域
         */
        if (type =='4f4e0a8b3aa14ef686c5db21f10dd419' ) {
          project.locationType = 'ground_west';
        } else if (type =='c32df338e2ae4f74a728c4649bfc4588' ){
          project.locationType = 'sea';
        } else {
          project.locationType = 'ground_east'
        }

      },
      // // 复制项目
      // copyProject() {
      //   if (!this.copyInfoDetail.srcId || this.copyInfoDetail.srcId == '') {
      //     this.isLoading = false;
      //     this.$message.warning("项目ID不允许为空")
      //     return;
      //   }
      //   this.isLoading = true;
      //   this.$post("/feasibility_data/copy/", this.copyInfoDetail, (data) => {
      //     this.$message.success('复制成功！');
      //     this.$refs['project_query_table'].reload();
      //   }, (response) => {
      //     this.isLoading = false;
      //     this.detailDlgVisible = false;
      //   });
      // },
      //修改项目类型监听
      handleChangeProjectType(type,project) {
        if(project.id) {
          //如果有id，认为是更新数据，不修改评价方法
          return;
        }
        //老区项目、提高采收率项目使用对减法
        if(type == 'eor'||type=='productivity_construction_old'||type=='scattered') {
          project.extraEvaluateMethod='subtract';
        } else{
          project.extraEvaluateMethod='';
        }
      },
      /**
       *导入文件解析
       */
      handleFileParseSuccess(workbook) {
        this.preEvaluationExcelData = excel.parseXlsxWorkbook(workbook);
      },
      beforeUpload(file) {
        this.files = file;
        const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (extension !== 'xlsx' && extension !== 'xls') {
          this.$message({
            message: '只能上传Excel（即后缀是.xlsx或者.xls)的文件.',
            type: 'warning'
          })
          return false;
        }
        if (isLt5M) {
          return true;
        }

        this.$message({
          message: '请不要上传大于5MB的文件.',
          type: 'warning'
        })
        return false;
      },
      importExcel(e){
        if(!e.target||!e.target.files||!e.target.files.length) {
          e.target.files = this.files;
          // return;
        }
        const loading = this.openLoading('正在处理...');
        let formData = new FormData();
        formData.append("multipartFile", e.target.files[0])
        this.$message.success('模拟保存成功！');
        loading.close();
        this.showFeaImport = false;
      },
      uploadFile() {
        // 装载成formData数据
        this.isLoading = true;
        this.excelLoading = true;
        const formData = new FormData();
        formData.append('file', this.files, this.files.name);
        formData.append('projectId', this.projectInfo.id);
        axios.post(Vue.prototype.$ctx+'/feasibility_data/pre_eva_file/upload',formData,{
          'Content-type' : 'multipart/form-data'
        }).then(response=>{
          if(response.data.code==0) {
            this.projectDetailData.preEvaluationFileId = response.data.data;
            this.excelLoading = true;
            this.$get('/feasibility_data/pre_eva_file/preview',{fileId:this.projectDetailData.preEvaluationFileId},(response)=>{
              this.projectDetailData.preEvaluationExcelData = response.data;
              this.preEvaluationExcelData = null;
            },()=>{
              this.excelLoading = false;
            });
            // this.$message.success("上传成功")
            this.showFeaImport = false;
          } else {
            this.$message.warning(response.data.msg);
          }
          this.isLoading = false;
          // 上传成功后的处理
        },err=>{
          console.error(err);
          this.$message.error("上传文件出错")
          this.isLoading = false;
          this.excelLoading = false;
          // 出现错误时的处理
        })
      },

      //生成报告
      createProjectReport: function (id) {
        window.open(this.$ctx+'/project/report/createReport?projectId=' + id);
      },

    },

  }
</script>
